package code.classic150on2025;

import utils.TreeNode;

import java.util.*;

public class BInSearchTree {
    // 230. 二叉搜索树中第 K 小的元素
    public int kthSmallest(TreeNode root, int k) {
        if (root == null)
            return -1;
        int pos = 0;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode node = root;
        while (!stack.isEmpty() || node != null) {
            while (node != null) {
                stack.push(node);
                node = node.left;
            }
            node = stack.pop();
            pos++;
            if (pos == k) {
                return node.val;
            }
            node = node.right;
        }
        return -1;
    }

    // 98. 验证二叉搜索树
    public boolean isValidBST(TreeNode root) {
        if (root == null)
            return true;
        return isValidDFS(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    private boolean isValidDFS(TreeNode node, long small, long big) {
        if (node == null)
            return true;
        if (node.val >= big || node.val <= small)
            return false;
        boolean left = isValidDFS(node.left, small, node.val);
        boolean right = isValidDFS(node.right, node.val, big);
        return left && right;
    }
}
